# -*- coding: utf-8 -*-

# @Time    : 2019-01-09 10:24
# @Author  : 小贰
# @FileName: zabbix_2_api.py
# @function: zabbix api for python 3.x

import json
import time
from urllib import request, parse
import redis


class zabbix_api:
    def __init__(self, url, user, passwd):
        self.url = url
        self.user = user
        self.passwd = passwd
        self.header = {"Content-Type": "application/json"}

    def user_login(self):
        data = {
            "jsonrpc": "2.0",
            "method": "user.login",
            "params": {
                "user": self.user,
                "password": self.passwd
            },
            "id": 0
        }
        # 由于API接收的是json字符串，故需要转化一下
        data = json.dumps(data).encode('utf-8')
        # 对请求进行包装
        req = request.Request(self.url, headers=self.header, data=data)
        try:
            # 打开包装过的url
            result = request.urlopen(req)
        except Exception as e:
            print("Auth Failed, Please Check Your Name And Password:", e)
        else:
            response = result.read()
            # 上面获取的是bytes类型数据，故需要decode转化成字符串
            page = response.decode('utf-8')
            # 将此json字符串转化为python字典
            page = json.loads(page)
            self.authID = page['result']
            result.close()
            return self.authID

    def main(self, method, params):
        data = {
            "jsonrpc": "2.0",
            "method": method,
            "params": params,
            "auth": self.user_login(),
            "id": 1
        }
        data = json.dumps(data).encode("utf-8")
        req = request.Request(self.url, headers=self.header, data=data)

        try:
            result = request.urlopen(req)
        except Exception as e:
            print('Error code: ', e)
        else:
            response = result.read()
            # 上面获取的是bytes类型数据，故需要decode转化成字符串
            page = json.dumps(json.loads(response.decode('utf-8')), indent=4, ensure_ascii=False)

            return page


def get_problem(url, user, passwd):
    zabbix = zabbix_api(url, user, passwd)
    method = "trigger.get"
    params = {
        "output": "extend",
        "filter": {
            "value": 1
        },
        "sortfield": "priority",
        "sortorder": "DESC",
        "skipDependent": 1,
        "monitored": 1,
        "active": 1,

        "expandDescription": 1,
        "selectHosts": ["host", "name"],
        "selectGroups": ['name'],
    }
    result = zabbix.main(method, params)

    result = json.loads(result)["result"]
    data_list = []
    if result:
        for j in result:
            timeArray = time.localtime(int(j["lastchange"]))
            date_str = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
            data_list.append([date_str, j["hosts"][0]["name"], j["description"], j["priority"]])
    return data_list


def get_host_items(url, user, passwd):
    params = {
        "output": "extend",
        "hostids": "10297",
        "search": {
            "key_": "game.status[5306,peak.race]"
        },
        "sortfield": "name"
    }

    zabbix = zabbix_api(url, user, passwd)
    method = "item.get"
    result = zabbix.main(method, params)
    return result


def get_host_group(url, user, passwd):
    params = {
        "output": "extend"
    }

    zabbix = zabbix_api(url, user, passwd)
    method = "hostgroup.get"
    result = zabbix.main(method, params)
    return result


def get_templates(url, user, passwd):
    params = {
        "output": ["name"]
    }

    zabbix = zabbix_api(url, user, passwd)
    method = "template.get"
    result = zabbix.main(method, params)
    return result


def get_host(url, user, passwd, host_name):
    params = {
        "output": ["hostid"],
        "selectParentTemplates": ["name"],
        "selectGroups": ["name"],
        "filter": {
            "host": host_name
        }
    }

    zabbix = zabbix_api(url, user, passwd)
    method = "host.get"
    result = zabbix.main(method, params)
    return result


def create_host(url, user, passwd, params):
    zabbix = zabbix_api(url, user, passwd)
    method = "host.create"
    result = zabbix.main(method, params)
    return result


def update_host(url, user, passwd, params):
    zabbix = zabbix_api(url, user, passwd)
    method = "host.update"
    result = zabbix.main(method, params)
    return result


def get_host_ip(url, user, passwd, ip):
    params = {
        "output": ["hostid"],
        "filter": {
            'ip':[ip]
        }
    }

    zabbix = zabbix_api(url, user, passwd)
    method = "host.get"
    result = zabbix.main(method, params)
    return result

def del_host(url, user, passwd, hostid):
    params = [hostid]
    zabbix = zabbix_api(url, user, passwd)
    method = "host.delete"
    result = zabbix.main(method, params)
    return result


if __name__ == "__main__":
    import json
    url = 'http://192.168.1.134/zabbix/api_jsonrpc.php'
    user = "Admin"
    passwd = "zabbix"
    ret = get_problem(url, user, passwd)
    print(ret)